import csv
import json


def jaccard_coefficient(a, b_string):
    """ using x/1.0 to convert float. """
    b = b_string.split(',')
    intersection_size = len(intersect(a, b))/1.0
    union_size = len(union(a, b))/1.0
    return intersection_size/union_size

def intersect(a, b):
    """ return the intersection of two lists """
    return list(set(a) & set(b))


def union(a, b):
    """ return the union of two lists """
    return list(set(a) | set(b))


def arithmetic_mean(a, b):
    """ return the arithmetic mean of two numbers """
    return (a + b)/2.0


def weighted_sum(a, b):
    """ return the weighted sum of two numbers """
    return (a + b)/2.0


def age_proximity(a, range_b):
    range_b_list = range_b.split('-')
    age_mean = arithmetic_mean(int(range_b_list[0]), int(range_b_list[1]))
    age_variation = int(range_b_list[1]) - int(range_b_list[0])
    factor = 10**(len(str(age_variation)) - 1)
    return (((((int(a) - age_mean)**2) * -1)/(factor * age_variation)) + 100) / 100.0


def gender_proximity(a, b):
    if b.lower() == 'u':
        return 0.75
    elif a.lower() == b.lower():
        return 1
    else:
        return 0.25


def walk_of_life_proximity(a, range_b):
    range_b_list = range_b.split(',')
    if any(a.lower() in s for s in range_b_list):
        return 1
    else:
        return 0.5


def get_similarity_and_time():
    participants_file = open("participants.json")
    results_file = open("allresults.json")
    participants_json = json.load(participants_file)
    results_json = json.load(results_file)

    user_similarities = []
    for i in range(len(participants_json)):
        for j in range(len(results_json[i])):
            walk_of_life_coefficient = walk_of_life_proximity(participants_json[0]['walkOfLife'], results_json[i][j]['ad']['walkOfLife'])
            m_jaccard_coefficient = jaccard_coefficient(participants_json[0]['likes'], results_json[i][j]['ad']['categories'])
            gender_coefficient = gender_proximity(participants_json[0]['gender'], results_json[i][j]['ad']['gender'])
            age_coefficient = age_proximity(participants_json[0]['age'], results_json[i][j]['ad']['age'])
            similarity = (walk_of_life_coefficient + m_jaccard_coefficient + gender_coefficient + age_coefficient) / 4.0

            if results_json[i][j]['answerTimeMillis'] != -1:
                time_in_seconds = ((int(results_json[i][j]['answerTimeMillis']) - int(results_json[i][j]['notificationTimeMillis'])) / 1000) / 60.0
                user_similarities.append((int(similarity * 100), time_in_seconds))

    return user_similarities


if __name__ == '__main__':

    similarities_and_times = get_similarity_and_time()

    with open('eggs.csv', 'wb') as csvfile:
        spamwriter = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
        spamwriter.writerow(['similarity', 'answer_time'])
        for tuple in similarities_and_times:
            spamwriter.writerow([tuple[0], tuple[1]])